from typing import List
import os

class Resource:
    """
    资源: 只读的文件或文件夹。
    """
    def __init__(self, where:str, type:str) -> None:
        self.where = where
        self.type = type
        self.name = ""
        self.postfix = ""
        self.children = {}
        self.file = None
    
    def read(self) -> None:
        if self.type=="file": 
            self.close()
            self.file = open(self.where,"r",encoding="utf-8")
    
    def close(self) -> None:
        if self.file:
            self.file.close()
            self.file = None

    # 文件夹方法
    def get(self, name) -> "Resource":   
        return self.children.get(name,None)

    def create(where:str) -> "Resource":
        r = Resource(where,"file" if os.path.isfile(where) else "folder")
        Resource.createFromResource(r)
        return r
    
    # 好看些
    def __repr__(self) -> str:
        return '<Resource where="{}" type="{}" name="{}" postfix="{}">'.format(self.where,self.type,self.name,self.postfix)

    @staticmethod
    def createFromResource(where:"Resource") -> None:
        for filename in os.listdir(where.where):
            file_path = os.path.realpath( os.path.join(where.where,filename) )
            isfile = os.path.isfile(file_path)

            where.children[filename] = r = Resource(file_path,"file" if isfile else "folder")

            if isfile: 
                name, postfix = filename.split(".",1)
                r.name = name
                r.postfix=postfix  
            
            if not isfile: Resource.create(r)
